//
//  LYSelectYearMonthPicker.m
//  BMPickView
//
//  Created by liuyan on 19/4/20.
//  Copyright © 2017年 Daredos. All rights reserved.
//

#import "LYSelectYearMonthPicker.h"

#define LYScreenHeight   [UIScreen mainScreen].bounds.size.height
#define LYScreenWidth    [UIScreen mainScreen].bounds.size.width
#define LYColorWithRGB(r, g, b)  [UIColor colorWithRed:(r) / 255.f green:(g) / 255.f blue:(b) / 255.f alpha:1.f]

@interface LYSelectYearMonthPicker ()<UIPickerViewDataSource, UIPickerViewDelegate>

@property (nonatomic, strong) UIButton *cancleButton;
@property (nonatomic, strong) UIButton *sureButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIPickerView *pickView;


@property (nonatomic, strong) NSArray *dateArray;
@property (nonatomic, strong) NSArray *selectArray;

@property (nonatomic, assign) NSInteger minYearString;
@property (nonatomic, assign) NSInteger minMonthString;

@property (nonatomic, copy) SureActionBlock sureblock;

@property (nonatomic, strong) UIView *coverView;

@property (nonatomic, assign) BOOL isShowCurrent;

@end


@implementation LYSelectYearMonthPicker

#pragma mark -- LazyLoad
-(NSArray *)dateArray
{
    if (!_dateArray) {
        
        NSDateFormatter *customDateFormatter = [[NSDateFormatter alloc] init];
        
        [customDateFormatter setDateFormat:@"yyyy"];
        NSInteger year = [[customDateFormatter stringFromDate:[NSDate date]] integerValue];
        
        [customDateFormatter setDateFormat:@"MM"];
        NSInteger month = [[customDateFormatter stringFromDate:[NSDate date]] integerValue];
        
        NSMutableArray *yearArray = [NSMutableArray array];
        for (NSInteger i = self.minYearString; i <= year; i++) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            dict[@"year"] = [NSString stringWithFormat:@"%li", i];
            NSMutableArray *array = [NSMutableArray array];
            if (i == self.minYearString) {
                if (self.minYearString == year) {
                    for (NSInteger j = self.minMonthString; j <= month; j++) {
                        [array addObject:[NSString stringWithFormat:@"%li", j]];
                    }
                    dict[@"month"] = array;
                }else{
                    for (NSInteger j = self.minMonthString; j <= 12; j++) {
                        [array addObject:[NSString stringWithFormat:@"%li",j]];
                    }
                    dict[@"month"] = array;
                }
            }else if(i == year){
                for (NSInteger j = 1; j <= month; j++) {
                    [array addObject:[NSString stringWithFormat:@"%li",j]];
                }
                dict[@"month"] = array;
            }else{
                NSArray *a = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12"];
                array = [NSMutableArray arrayWithArray:a];
                dict[@"month"] = array;
            }
            
            [yearArray addObject:dict];
        }
        
        if (self.isShowCurrent) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            dict[@"year"] = @"至今";
            dict[@"month"] = @[@""];
             [yearArray addObject:dict];
        }
        
        _dateArray = [NSArray arrayWithArray:yearArray];
    }
    return _dateArray;
}


#pragma mark -- Init

+ (instancetype)actionPickerMinDate:(NSInteger)mindYear minMonth:(NSInteger)minMonth isShowCurrent:(BOOL)isShow sureBlock:(SureActionBlock)sureblock{
    LYSelectYearMonthPicker *picker = [[LYSelectYearMonthPicker alloc] initActionPickerMinDate:mindYear minMonth:minMonth isShowCurrent:isShow sureBlock:sureblock];
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:picker.coverView];
    [keyWindow addSubview:picker];
    picker.transform = CGAffineTransformMakeScale(0, 0);
    [UIView animateWithDuration:.5f
                          delay:0
         usingSpringWithDamping:1.0
          initialSpringVelocity:1
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
                         picker.coverView.alpha = 0.4;
                         picker.transform = CGAffineTransformIdentity;
                     } completion:^(BOOL finished) {
                     }];
    return picker;
}

- (instancetype)initActionPickerMinDate:(NSInteger)mindate minMonth:(NSInteger)minMonth isShowCurrent:(BOOL)isShow sureBlock:(SureActionBlock)sureblock{
    self = [super init];
    if (self) {
        self.isShowCurrent = isShow;
        self.minYearString = mindate;
        self.minMonthString = minMonth;
        self.sureblock = sureblock;
        self.frame = CGRectMake(0, LYScreenHeight - 280, LYScreenWidth, 278);
        self.backgroundColor = [UIColor whiteColor];
        [self createSubview];
    }
    return self;
}

- (void)createSubview{
    if (!_pickView) {
        _pickView = [[UIPickerView alloc] initWithFrame:CGRectMake(10, 10, LYScreenWidth - 20, 214)];
        _pickView.backgroundColor = [UIColor whiteColor];
        _pickView.dataSource = self;
        _pickView.delegate = self;
        _pickView.showsSelectionIndicator = YES;
        [self addSubview:_pickView];
        
    }
    
    if (!_cancleButton) {
        _cancleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancleButton.frame = CGRectMake(0,234, WIDTH/2, 44);
        _cancleButton.backgroundColor = [UIColor whiteColor];
        [_cancleButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancleButton setTitleColor:LYColorWithRGB(153, 153, 153) forState:UIControlStateNormal];
        [_cancleButton addTarget:self action:@selector(hideSelf) forControlEvents:UIControlEventTouchUpInside];
        _cancleButton.titleLabel.font = [UIFont systemFontOfSize:18];
        [self addSubview:_cancleButton];
    }
    
    if (!_sureButton) {
        _sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _sureButton.frame = CGRectMake(_cancleButton.right,  234, WIDTH/2, 44);
        _sureButton.backgroundColor = [UIColor whiteColor];
        [_sureButton setTitle:@"确定" forState:UIControlStateNormal];
        [_sureButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [_sureButton addTarget:self action:@selector(sureButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _sureButton.titleLabel.font = [UIFont systemFontOfSize:18];
        [self addSubview:_sureButton];
    }
    
    UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(_cancleButton.right, _cancleButton.top, 1, _cancleButton.height)];
    lineview.backgroundColor = RGB(247, 247, 247);
    [self addSubview:lineview];

    UIView *lineview1 = [[UIView alloc] initWithFrame:CGRectMake(0, _cancleButton.top-1, WIDTH, 1)];
    lineview1.backgroundColor = RGB(247, 247, 247);
    [self addSubview:lineview1];
    
    CGFloat height = [_pickView rowSizeForComponent:0].height;
    NSInteger maxRow1 = self.dateArray.count-1;
    NSInteger maxRow2 = [self.dateArray.lastObject[@"month"] count]-1;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.pickView selectRow:maxRow1 inComponent:0 animated:NO];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self pickerView:self.pickView didSelectRow:maxRow2 inComponent:0];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.pickView selectRow:maxRow2 inComponent:1 animated:NO];
            });
        });
    });
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    return 2;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    if (component == 0) {
        return self.dateArray.count;
    }else {
        NSInteger seleProIndx = [pickerView selectedRowInComponent:0];
        NSDictionary *dict = self.dateArray[seleProIndx];
        NSArray *array = dict[@"month"];
        self.selectArray = [NSArray arrayWithArray:array];
        return self.selectArray.count;
    }
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        NSDictionary * city = self.dateArray[row];
        return city[@"year"];
    }else{
        return self.selectArray[row];
    }
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    if (component == 0) {
        [pickerView reloadComponent:1];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 30;
}

- (void)sureButtonClick:(UIButton *)button
{
    NSInteger i = [self.pickView selectedRowInComponent:0];
    NSInteger j = [self.pickView selectedRowInComponent:1];
    NSString *str1 = self.dateArray[i][@"year"];

    NSString *str2 = self.dateArray[i][@"month"][j];
    NSInteger ind2 = str2.integerValue;
    NSString *string = @"";
    if (ind2 <= 9) {
        string = [NSString stringWithFormat:@"%li-0%li",str1.integerValue,ind2];
    }else{
        string = [NSString stringWithFormat:@"%li-%li",str1.integerValue,ind2];
    }
    self.sureblock(string);
    [self hideSelf];
}


/**
 隐藏视图
 */
-(void)hideSelf{
    [UIView animateWithDuration:.4f
                          delay:0
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^{
//                         self.transform = CGAffineTransformMakeScale(0, 0);
//                         self.coverView.alpha = 0;
                     }
                     completion:^(BOOL finished) {
                         [self.coverView removeFromSuperview];
                         [self removeFromSuperview];
                     }];
}


- (UIView *)coverView {
    if (_coverView == nil) {
        _coverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth, LYScreenHeight)];
        _coverView.backgroundColor = [UIColor blackColor];
        _coverView.alpha = 0;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideSelf)];
        [_coverView addGestureRecognizer:tap];
    }
    return _coverView;
}

@end
